// 引入express
var express = require('express')
var multipart = require('connect-multiparty')
var multipartMiddleware = multipart()
// 引入数据库
var mysql = require('../dataBase')
// 定义路由
var app = express.Router()
// 引入multer
var multer = require('multer')
// 引入path模块
var path = require('path')
// 引入fs模块
var fs = require('fs')
const { error } = require('console')
// 设置全局变量 定义时间戳
var timestamp = ''
// 设置全局变量 定义文件路径名
var destination = '/uploads'
// // 设置全局变量  定义文件名
var filename = ''
// 设置图片存储路径
var storage = multer.diskStorage({
  // destination是一个字符串，确定上传文件的物理路径
  destination: __dirname + '/../public/' + destination, //上传的相对路径
  filename: (req, file, cb) => {
    // 自定义设置图片名
    timestamp = new Date().getTime() //根据上传时间的unix(时间戳)来命名
    //设置文件名 // file.originalname.split('.')[1]获取文件的扩展名
    filename = 'upload-' + timestamp + '.' + file.originalname.split('.')[1]
    cb(null, filename)
  },
})
// 创建接收文件夹
const upload = multer({ storage: storage })

// 添加图片
app.post('/upload', upload.single('file'), (req, res) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header(
    'Access-Control-Allow-Methods',
    'PUT, GET, POST, DELETE, OPTIONS,form',
  )
  res.header('Access-Control-Allow-Headers', 'X-Requested-With')
  res.header('Access-Control-Allow-Headers', 'Content-Type')
  var $id = req.body.id
  var url = destination + '/' + filename //写入数据库的路径
  console.log(url, req.body)
  var sql = `update userList set img='${url}' where id=${$id}`
  mysql.query(sql, (err, result) => {
    res.send({ state: 'OK', data: { url } })
  })
})
// 注册
app.post('/register', multipartMiddleware, (req, res) => {
  let $name = req.body.u_name
  let $password = req.body.password
  let $phone = req.body.phone
  let $account = req.body.account
  let $sex = req.body.sex
  let $jurisdiction = req.body.jurisdiction
  let $passCode = req.body.passCode
  let selectSql = `SELECT * from userList WHERE account ='${$account}'`
  mysql.query(selectSql, (err, result) => {
    let str = result.toString()
    //   console.log(err,result,str)
    if (str) {
      res.send({ state: 'error', data: '该账号已被注册' })
    }
  })
  //   获取当前日期
  var today = new Date()
  var y = today.getFullYear()
  var m = today.getMonth() + 1
  var d = today.getDate()
  var h = today.getHours()
  var i = today.getMinutes()
  var s = today.getSeconds()
  m = m < 10 ? '0' + m : m
  d = d < 10 ? '0' + d : d
  h = h < 10 ? '0' + h : h
  i = i < 10 ? '0' + i : i
  s = s < 10 ? '0' + s : s
  let dateStr = `${y}年${m}月${d}日${h}时${i}分${s}秒`
  let sql = `insert into userList(account,name,password,phone,email,sex,createTime,jurisdiction,passCode)values('${$account}','${$name}','${$password}','${$phone}'
  ,'','${$sex}','${dateStr}','${$jurisdiction}','${$passCode}')`
  mysql.query(sql, (err, result) => {
    res.send({
      state: 'OK',
      data: {
        u_name: $name,
        account: $account,
        phone: $phone,
        jurisdiction: $jurisdiction,
      },
    })
  })
})
// 登录接口
app.post('/login', multipartMiddleware, (req, res) => {
  let $account = req.body.account
  let $pass = req.body.pass
  let sql = `SELECT * from userList WHERE account ='${$account}' and password='${$pass}'
    `
  mysql.query(sql, (err, result) => {
    // let str = result.toString()
    if (result && result[0]) {
      let account = result[0].account
      let pass = result[0].password
      let name = result[0].name
      let phone = result[0].phone
      let sex = result[0].sex
      let jur = result[0].jurisdiction
      let id = result[0].id
      let img = result[0].img
      if ($pass === pass && $account === account) {
        res.send({
          state: 'OK',
          data: {
            u_id: id,
            u_name: name,
            u_account: account,
            u_phone: phone,
            u_sex: sex,
            u_jurisdiction: jur,
            u_img: img,
          },
        })
      }
    } else {
      res.send({ state: 'error', data: '账号或密码错误，请检查后重新输入!' })
    }
  })
})
// 修改密码
app.post('/updatePass', multipartMiddleware, (req, res) => {
  let $account = req.body.account
  let $pass = req.body.pass
  let $passCode = req.body.passCode
  let sql = `update userList set password='${$pass}' where account='${$account}' and passCode='${$passCode}'`
  mysql.query(sql, (err, result) => {
    let str = result.toString()
    if (result.changedRows === 1) {
      res.send({ state: 'OK', data: '修改密码成功' })
    } else {
      res.send({ state: 'error', data: '修改密码失败！' })
    }
  })
})
// 发送验证码
app.post('/getCode', multipartMiddleware, async (req, res) => {
  const phone = req.phone
  const code = (n, m) => {
    return parseInt(Math.random() * (m - n) + n)
  }
  res.send({ phone: phone, code: code(1000, 9999) })
})

module.exports = app
